package com.xw.service.impl;

import com.xw.service.WebSocketServerService;
import org.springframework.stereotype.Service;
import javax.websocket.Session;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description: 针对表【user】的数据库操作Service实现
 * @Author: 72478
 * @Date: 2024/12/18 16:53
 * @Version: 1.0
 */
@Service
public class WebSocketServerServiceImpl implements WebSocketServerService {
    private static final ConcurrentHashMap<String, Session> ONLINE_USERS = new ConcurrentHashMap<>();

    @Override
    public void sendMessage(String userId, String message) throws IOException {
        Session session = ONLINE_USERS.get(userId);
        if (session != null && session.isOpen()) {
            session.getAsyncRemote().sendText(message);
        }
    }

    @Override
    public void sendMessageAll(String message) {
        for (Session session : ONLINE_USERS.values()) {
            session.getAsyncRemote().sendText(message);
        }
    }

    @Override
    public void sendMessageAll(String message, String userId) throws IOException {
        for (Session session : ONLINE_USERS.values()) {
            if (!session.getId().equals(userId)) {
                session.getAsyncRemote().sendText(message);
            }
        }
    }
}